package com.top145;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;

//https://leetcode.cn/problems/basic-calculator-ii/solutions/953012/ji-ben-ji-suan-qi-ii-shuang-zhan-chao-xi-s2ha/?envType=featured-list&envId=2ckc81c%3FenvType%3Dfeatured-list&envId=2ckc81c
public class Solution227 {
    LinkedList<Integer> nums = new LinkedList<>();
    LinkedList<Character> op = new LinkedList<>();
    HashMap<Character, Integer> map = new HashMap<>();

    public int calculate(String s) {
        s = "0" + s;
        map.put('+', 1);
        map.put('-', 1);
        map.put('*', 2);
        map.put('/', 2);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ' ') continue;
            if (c >= '0' && c <= '9') {
                int x = 0;
                while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                    x = 10 * x + s.charAt(i++) - '0';
                }
                i--;
                nums.addLast(x);
            } else {
                while (!op.isEmpty() && map.get(op.getLast()) >= map.get(c)) cacl();
                op.addLast(c);
            }
        }
        while (!op.isEmpty()) cacl();
        return nums.getLast();
    }

    public void cacl() {
        Integer n2 = nums.removeLast();
        Integer n1 = nums.removeLast();
        Character pop = op.removeLast();
        if (pop == '+') nums.addLast(n1 + n2);
        else if (pop == '-') nums.addLast(n1 - n2);
        else if (pop == '*') nums.addLast(n1 * n2);
        else nums.addLast(n1 / n2);
    }

}
